<template>
  <div class="practice-container">
    <!-- 页面标题 -->
    <section class="container">
      <header class="comm-title">
        <h2 class="fl tac">
          <span class="c-333">{{ currentSubjectTitle }} - 刷题练习</span>
        </h2>
      </header>
      
      <!-- 刷题区域 -->
      <div v-if="!showResult" class="practice-area">
        <!-- 题目进度 -->
        <div class="question-progress">
          <span>题目 {{ currentIndex + 1 }} / {{ questionList.length }}</span>
        </div>
        
        <!-- 题目内容 -->
        <div class="question-content">
          <h3 class="question-title">{{ currentQuestion.title }}</h3>
          
          <!-- 题目选项 -->
          <div class="question-options">
            <ul>
              <li 
                v-for="option in options" 
                :key="option.key"
                :class="{
                  'option-item': true,
                  'selected': userAnswers[currentQuestion.id] === option.key,
                  'correct': showAnswer && currentQuestion.answer === option.key,
                  'incorrect': showAnswer && userAnswers[currentQuestion.id] === option.key && userAnswers[currentQuestion.id] !== currentQuestion.answer
                }"
                @click="selectOption(option.key)"
              >
                <span class="option-label">{{ option.key }}.</span>
                <span class="option-content">{{ option.content }}</span>
              </li>
            </ul>
          </div>
          
          <!-- 答案解析 -->
          <div v-if="showAnswer" class="question-analysis">
            <div class="analysis-title">解析：</div>
            <div class="analysis-content">{{ currentQuestion.analysis }}</div>
          </div>
          
          <!-- 翻页按钮 -->
          <div class="navigation-buttons">
            <button 
              class="nav-btn prev-btn" 
              :disabled="currentIndex === 0"
              @click="prevQuestion"
            >
              ← 上一题
            </button>
            
            <button 
              v-if="!showAnswer && userAnswers[currentQuestion.id]"
              class="nav-btn submit-btn"
              @click="submitAnswer"
            >
              确认答案
            </button>
            
            <button 
              v-if="showAnswer && currentIndex < questionList.length - 1"
              class="nav-btn next-btn"
              @click="nextQuestion"
            >
              下一题 →
            </button>
            
            <button 
              v-if="showAnswer && currentIndex === questionList.length - 1"
              class="nav-btn finish-btn"
              @click="finishPractice"
            >
              完成练习
            </button>
          </div>
        </div>
      </div>
      
      <!-- 结果汇总 -->
      <div v-else class="result-summary">
        <h2>练习完成！</h2>
        <div class="summary-stats">
          <div class="stat-item">
            <span class="stat-label">总题数：</span>
            <span class="stat-value">{{ questionList.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">正确题数：</span>
            <span class="stat-value correct">{{ correctCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">错误题数：</span>
            <span class="stat-value incorrect">{{ questionList.length - correctCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">正确率：</span>
            <span class="stat-value">{{ correctRate }}%</span>
          </div>
        </div>
        
        <div class="result-actions">
          <button class="action-btn restart-btn" @click="restartPractice">重新练习</button>
          <button class="action-btn back-btn" @click="backToSubject">返回选题</button>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import courseApi from '@/api/course'
import questionApi from '@/api/question'

export default {
  data() {
    return {
      subjectId: '',
      subjectList: [], // 所有课程分类
      currentSubjectTitle: '', // 当前选中分类标题
      questionList: [], // 题目列表
      currentIndex: 0, // 当前题目索引
      userAnswers: {}, // 用户答案记录
      showAnswer: false, // 是否显示答案和解析
      showResult: false, // 是否显示结果汇总
      correctCount: 0, // 正确题目数
      correctRate: 0 // 正确率
    }
  },
  
  computed: {
    // 当前题目
    currentQuestion() {
      return this.questionList[this.currentIndex] || {}
    },
    
    // 当前题目选项
    options() {
      const question = this.currentQuestion
      const opts = []
      
      if (question.optionA) {
        opts.push({ key: 'A', content: question.optionA })
      }
      if (question.optionB) {
        opts.push({ key: 'B', content: question.optionB })
      }
      if (question.optionC) {
        opts.push({ key: 'C', content: question.optionC })
      }
      if (question.optionD) {
        opts.push({ key: 'D', content: question.optionD })
      }
      
      return opts
    }
  },
  
  created() {
    this.subjectId = this.$route.query.subjectId
    if (this.subjectId) {
      this.initData()
    }
  },
  
  methods: {
    // 初始化数据
    initData() {
      // 获取所有课程分类
      courseApi.getNestedTreeList().then(response => {
        this.subjectList = response.data
        
        // 查找当前选中分类的标题
        this.findSubjectTitle(this.subjectList, this.subjectId)
        
        // 获取题目列表
        this.fetchQuestions()
      })
    },
    
    // 查找分类标题
    findSubjectTitle(list, id) {
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.id === id) {
          this.currentSubjectTitle = item.title
          return
        }
        if (item.children && item.children.length > 0) {
          this.findSubjectTitle(item.children, id)
        }
      }
    },
    
    // 获取题目列表
    fetchQuestions() {
      questionApi.getQuestionListByCourseId(this.subjectId).then(response => {
        this.questionList = response.data.rows || []
        if (this.questionList.length === 0) {
          // 如果按课程ID查不到，尝试按章节ID查询
          questionApi.getQuestionListByChapterId(this.subjectId).then(res => {
            this.questionList = res.data.rows || []
          })
        }
      })
    },
    
    // 选择选项
    selectOption(optionKey) {
      // 如果已经显示答案，则不能更改选择
      if (this.showAnswer) return
      
      // 记录用户答案
      this.$set(this.userAnswers, this.currentQuestion.id, optionKey)
    },
    
    // 提交答案
    submitAnswer() {
      this.showAnswer = true
    },
    
    // 上一题
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--
        this.showAnswer = !!this.userAnswers[this.currentQuestion.id]
      }
    },
    
    // 下一题
    nextQuestion() {
      if (this.currentIndex < this.questionList.length - 1) {
        this.currentIndex++
        this.showAnswer = !!this.userAnswers[this.currentQuestion.id]
      }
    },
    
    // 完成练习
    finishPractice() {
      // 计算正确题目数
      this.correctCount = 0
      this.questionList.forEach(question => {
        if (this.userAnswers[question.id] === question.answer) {
          this.correctCount++
        }
      })
      
      // 计算正确率
      this.correctRate = this.questionList.length > 0 
        ? Math.round((this.correctCount / this.questionList.length) * 100) 
        : 0
      
      // 显示结果汇总
      this.showResult = true
    },
    
    // 重新练习
    restartPractice() {
      this.currentIndex = 0
      this.userAnswers = {}
      this.showAnswer = false
      this.showResult = false
      this.correctCount = 0
      this.correctRate = 0
    },
    
    // 返回选题页面
    backToSubject() {
      this.$router.push({ path: '/practice' })
    }
  }
}
</script>

<style scoped>
.practice-container {
  background-color: #f5f5f5;
  min-height: calc(100vh - 200px);
  padding: 20px 0;
}

.practice-area {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.question-progress {
  text-align: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
  font-size: 16px;
  color: #666;
}

.question-title {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
  line-height: 1.5;
}

.question-options ul {
  list-style: none;
  padding: 0;
}

.option-item {
  padding: 12px 15px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.option-item:hover {
  background-color: #f0f8ff;
  border-color: #00aaff;
}

.option-item.selected {
  background-color: #e3f2fd;
  border-color: #2196f3;
}

.option-item.correct {
  background-color: #e8f5e9;
  border-color: #4caf50;
}

.option-item.incorrect {
  background-color: #ffebee;
  border-color: #f44336;
}

.option-label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 20px;
}

.option-content {
  flex: 1;
}

.question-analysis {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border-left: 4px solid #4caf50;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.analysis-content {
  color: #666;
  line-height: 1.5;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
  flex-wrap: wrap;
}

.nav-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  min-width: 100px;
}

.nav-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.prev-btn {
  background-color: #fff;
  color: #333;
  border: 1px solid #ddd;
}

.prev-btn:hover:not(:disabled) {
  background-color: #f5f5f5;
}

.submit-btn {
  background-color: #4caf50;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.next-btn {
  background-color: #2196f3;
  color: white;
}

.next-btn:hover:not(:disabled) {
  background-color: #0b7dda;
}

.finish-btn {
  background-color: #ff9800;
  color: white;
}

.finish-btn:hover:not(:disabled) {
  background-color: #e68a00;
}

.result-summary {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.result-summary h2 {
  margin-bottom: 30px;
  color: #333;
}

.summary-stats {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 30px;
}

.stat-item {
  margin: 10px 20px;
}

.stat-label {
  font-weight: bold;
  color: #666;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
}

.stat-value.correct {
  color: #4caf50;
}

.stat-value.incorrect {
  color: #f44336;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.action-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.restart-btn {
  background-color: #4caf50;
  color: white;
}

.restart-btn:hover {
  background-color: #45a049;
}

.back-btn {
  background-color: #2196f3;
  color: white;
}

.back-btn:hover {
  background-color: #0b7dda;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .practice-container {
    padding: 10px;
  }
  
  .practice-area {
    padding: 15px;
  }
  
  .question-title {
    font-size: 16px;
  }
  
  .option-item {
    padding: 10px;
  }
  
  .navigation-buttons {
    flex-direction: column;
    gap: 10px;
  }
  
  .nav-btn {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .result-summary {
    padding: 20px;
  }
  
  .summary-stats {
    flex-direction: column;
  }
  
  .result-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>